package com.hbsoft.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URL;

import com.hb.bean.CallResult;
import com.hb.bean.FileValue;
import com.hb.config.Config;
import com.hb.util.DateUtil;
import com.hb.util.StringUtil;
import com.hbsoft.config.SysConfigInfo;

import net.iharder.Base64;

/**
 * 文件操作工具类
 * 
 * @author yyp
 * @date 2018年5月10日下午9:22:03
 */
public class FileUtil {
	
	public static void main(String[] args) {
		String name = System.getProperty("os.name");
		System.out.println(name.toLowerCase().indexOf("windows"));
	}

	/**
	 * 获取upload路径
	 * 
	 * @date 2018年5月11日下午3:15:03
	 * @param fileName
	 *            传入上传文件名称
	 * @return
	 */
	public static CallResult<FileValue> getUploadPath(String fileName) {
		CallResult<FileValue> result = new CallResult<FileValue>();
		if (fileName == null) {
			result.setCode(400);
			result.setMessage("文件名为空");
		} else if ("".equals(fileName)) {
			result.setCode(400);
			result.setMessage("文件名不能是空字符串");
		} else if (fileName.lastIndexOf(".") <= 0) {
			result.setCode(400);
			result.setMessage("文件不能没有后缀名");
		} else {
			String systemName = Config.PROJECTNAME;
			StringBuffer sb = new StringBuffer();
			String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
			if (System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0) {
				path = path.replace("%20", " ");
			} else {
				path = path.substring(1).replace("%20", " ");
			}
			int len = path.indexOf("webapps");
			if (len >= 0) {
				path = path.substring(0, len + 8);
				sb.append(path);
				sb.append(SysConfigInfo.uploadPath);
			} else {
				path = path.substring(0, 3);
				sb.append(path);
				sb.append("uploadFolder");
			}
			sb.append(File.separator);
			StringBuffer sbPath = new StringBuffer();
			sbPath.append("upload");
			sbPath.append(File.separator);
			if (systemName == null || "/".equals(systemName)) {
				sbPath.append("system");
			} else {
				sbPath.append(systemName.substring(1));
			}
			sbPath.append(File.separator);
			sbPath.append(DateUtil.get("y"));
			sbPath.append(File.separator);
			sbPath.append(DateUtil.get("M"));
			sbPath.append(File.separator);
			sbPath.append(DateUtil.get("d"));
			sbPath.append(File.separator);
			String fileNewName = fileName.substring(0, fileName.lastIndexOf(".")) + StringUtil.randomId()
					+ fileName.substring(fileName.lastIndexOf("."));
			sbPath.append(fileNewName);
			sb.append(sbPath);
			File file = new File(sb.toString());
			result.setCode(0);
			result.setMessage("成功");
			FileValue fileValue = new FileValue();
			fileValue.setFile(file);
			fileValue.setFileName(fileName);
			fileValue.setFileNewName(fileNewName);
			fileValue.setPath(sbPath.toString());
			result.setData(fileValue);
		}
		return result;
	}

	/**
	 * 创建文件目录
	 * 
	 * @date 2018年5月11日下午4:39:26
	 * @param file
	 */
	public static void createFolders(File file) {
		File parentFile = file.getParentFile();
		if (parentFile != null && !parentFile.exists()) {
			parentFile.mkdirs();
		}
	}

	/**
	 * 将图片转换成Base64编码
	 * 
	 * @date 2018年5月15日下午3:49:28
	 * @param imgFile
	 * @return
	 */
	public static String getImgStr(String imgFile) {
		String str = null;
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
			str = new String(Base64.encodeBytes(data));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * 将图片转换成Base64编码
	 * 
	 * @date 2018年5月15日下午3:51:33
	 * @param in
	 * @return
	 */
	public static String getImgStr(InputStream in) {
		byte[] data = null;
		if (in != null) {
			try {
				data = new byte[in.available()];
				in.read(data);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			data = new byte[1];
		}

		return new String(Base64.encodeBytes(data));
	}

	/**
	 * 对字节数组字符串进行Base64解码并生成图片
	 * 
	 * @param imgStr
	 *            图片数据
	 * @param imgFilePath
	 *            保存图片全路径地址
	 * @return
	 */
	public static boolean generateImage(String imgStr, String imgFilePath) {
		if (imgStr == null) // 图像数据为空
			return false;
		try {
			// Base64解码
			byte[] b = Base64.decode(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 输出字符串到指定文件
	 * 
	 * @date 2018年5月19日下午5:32:34
	 * @param file
	 *            文件
	 * @param data
	 *            要输出的数据
	 * @throws IOException
	 */
	public static void writer(File file, String data) throws IOException {
		createFolders(file);
		Writer out = null;
		try {
			out = new FileWriter(file);
			out.write(data);
			out.flush();
		} catch (IOException e) {
			throw e;
		} finally {
			if (out != null)
				out.close();
		}
	}

	public static void readHelp(String path) throws Exception {
		if (path.indexOf(".jar!") >= 0) {
			URL url = new URL("jar:" + path);
			BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
			String line = "";
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();
		} else {
			FileReader fr = new FileReader(path);
			char[] buf = new char[1024];
			int num = 0;
			while ((num = fr.read(buf)) != -1) {
				System.out.print(new String(buf, 0, num));
			}
			fr.close();
		}
	}

}
